package de.mssp.sensorkit.wlan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import de.mssp.sensorkit.R;

public class WLANActivity extends ListActivity implements OnClickListener 
{
	BroadcastReceiver receiver;
	WifiManager wifiMan;
	Button scanButton;
	List<WifiConfiguration> wifiList;
	WifiInfo conInfo;
	ArrayList<HashMap<String,String>> myNetworkList = new ArrayList<HashMap<String, String>>();
	SimpleAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wlan);

		//Register the Listener
		scanButton = (Button) findViewById(R.id.rescanButton);
		scanButton.setOnClickListener(this);
		
		//Set ListAdapter
		adapter = new SimpleAdapter(this, myNetworkList, R.layout.row_wlan, new String[] {"name", "level", "frequency"}, new int[] {R.id.nameCell, R.id.levelCell, R.id.frequencyCell});
		setListAdapter(adapter);
		
		// Get Informations about current Wifi-Connections
		wifiMan = (WifiManager) this.getSystemService(WIFI_SERVICE);
		conInfo = wifiMan.getConnectionInfo();

		// Register Broadcast Receiver
		if (receiver == null)
			receiver = new WiFiScanReceiver(this);
		registerReceiver(receiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		wifiMan.startScan();
	}

	/** Adds a network found by scanning to the ListView */
	protected void addNetworkToMap(ScanResult sr) {
		
		//Gather infos
		HashMap<String, String> map = new HashMap<String,String>();
		map.put("name", sr.SSID);
		map.put("level", "Level: "+String.valueOf(WifiManager.calculateSignalLevel(sr.level, 20))+"/20");
		map.put("frequency", "Frequency: "+String.valueOf(sr.frequency));
		
		myNetworkList.add(map);//Add result to datastore		
		adapter.notifyDataSetChanged();//Update List
	}

	@Override
	public void onPause() 
	{
		super.onPause();
		//Unregister for Scanresults
		unregisterReceiver(receiver);
	}

	@Override
	public void onResume() 
	{
		super.onResume();
		
		//Register for Scanresults
		registerReceiver(receiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
	}

	public void onClick(View view) 
	{
		//Rescan
		if (view.getId() == R.id.rescanButton) 
		{
			Toast.makeText(this, "Scanning for networks!", Toast.LENGTH_LONG).show();//Show Toast
			myNetworkList.clear();//Clear devicelist
			wifiMan.startScan();//Startscan
		}
	}
}
